package com.java2404.micro.pay.handler;


import com.java2404.micro.common.entity.Order;
import com.java2404.micro.common.resp.Result;
import com.java2404.micro.consumer.client.GatewayClient;
import com.java2404.micro.consumer.service.ConsumerService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private ConsumerService consumerService;

    @Autowired
    private GatewayClient gatewayClient; // 使用 OpenFeign 调用微服务

    /**
     * 用户支付接口
     * @param userId 用户ID
     * @param orderId 订单ID
     * @return Result
     */
    @GetMapping("/pay")
    @GlobalTransactional(name = "pay-order-tx", rollbackFor = Exception.class)
    public Result payOrder(@RequestParam("userId") Integer userId,
                           @RequestParam("orderId") Integer orderId) {
        // 1. 查询订单信息
        Order order = gatewayClient.getOrder(orderId);
        if (order == null || !order.getGstatus().equals(0)) {
            return Result.error("订单不存在或状态不正确");
        }

        // 2. 扣减用户余额
        consumerService.deductBalance(userId, order.getGprice());

        // 3. 更新订单状态为已付款
        order.setGstatus(2);  // 已付款
        Result updateResult = gatewayClient.updateOrder(order);
        if (updateResult.getCode()==0) {
            throw new RuntimeException("订单更新失败");
        }

        return Result.success("支付成功");
    }
}
